<template>
  <a-layout style="min-height: 100vh; background: #f8f9fa;">
    <!-- 顶部导航栏 -->
    <nav-bar />

    <a-layout style="max-width: 1600px; margin: 20px auto; width: 100%; padding: 0 16px;">
      <!-- 左侧会话列表 -->
      <a-layout-sider
        v-model:collapsed="sidebarCollapsed"
        :width="300"
        :collapsed-width="0"
        breakpoint="lg"
        style="background: #fff; margin-right: 20px; border-radius: 10px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.04);"
      >
        <chat-sidebar
          :sessions="sessions"
          :current-session-id="currentSessionId"
          :loading="sessionsLoading"
          @select="selectSession"
          @new="createNewSession"
          @delete="deleteSession"
        />
      </a-layout-sider>

      <!-- 主对话区域 -->
      <a-layout-content style="background: #fff; border-radius: 10px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.04);">
        <chat-panel
          :messages="currentMessages"
          :loading="messagesLoading"
          :sending="sending"
          @send="sendMessage"
        />
      </a-layout-content>
    </a-layout>
  </a-layout>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import NavBar from '../components/NavBar.vue'
import ChatSidebar from '../components/chat/ChatSidebar.vue'
import ChatPanel from '../components/chat/ChatPanel.vue'
import { chatAPI } from '../api/chat'

// 状态管理
const sidebarCollapsed = ref(false)
const sessions = ref([])
const sessionsLoading = ref(false)
const currentSessionId = ref(null)
const currentMessages = ref([])
const messagesLoading = ref(false)
const sending = ref(false)

// 加载会话列表
const loadSessions = async () => {
  sessionsLoading.value = true
  try {
    const response = await chatAPI.getSessions(1, 50)
    sessions.value = response.data.sessions
  } catch (error) {
    console.error('加载会话列表失败:', error)
    message.error('加载会话列表失败')
  } finally {
    sessionsLoading.value = false
  }
}

// 加载对话历史
const loadHistory = async (sessionId) => {
  messagesLoading.value = true
  try {
    const response = await chatAPI.getHistory(sessionId)
    // 确保消息格式正确，role字段必须是'user'或'assistant'
    const messages = (response.data.messages || []).map(msg => {
      // 确保role字段存在且有效
      if (!msg.role || (msg.role !== 'user' && msg.role !== 'assistant')) {
        console.warn('消息role字段无效:', msg)
        // 如果role字段缺失或无效，根据消息内容推断（这不是最佳实践，但作为后备）
        // 这里我们假设数据库中应该有正确的role，所以这种情况应该很少发生
        msg.role = 'assistant' // 默认设为assistant，但会记录警告
      }
      return msg
    })
    currentMessages.value = messages
  } catch (error) {
    console.error('加载历史记录失败:', error)
    message.error('加载历史记录失败')
  } finally {
    messagesLoading.value = false
  }
}

// 选择会话
const selectSession = async (sessionId) => {
  if (currentSessionId.value === sessionId) return
  
  currentSessionId.value = sessionId
  await loadHistory(sessionId)
}

// 创建新会话
const createNewSession = () => {
  currentSessionId.value = null
  currentMessages.value = []
  message.success('开始新对话')
}

// 删除会话
const deleteSession = async (sessionId) => {
  try {
    await chatAPI.deleteSession(sessionId)
    message.success('会话已删除')
    
    // 如果删除的是当前会话,清空
    if (currentSessionId.value === sessionId) {
      currentSessionId.value = null
      currentMessages.value = []
    }
    
    // 重新加载会话列表
    await loadSessions()
  } catch (error) {
    console.error('删除会话失败:', error)
    message.error('删除会话失败')
  }
}

// 发送消息
const sendMessage = async (text) => {
  if (!text.trim()) {
    message.warning('请输入消息')
    return
  }
  
  sending.value = true
  
  // 立即显示用户消息（确保role正确）
  const userMessage = {
    role: 'user',  // 明确设置为'user'
    content: text.trim(),
    created_at: new Date().toISOString()
  }
  console.log('添加用户消息:', userMessage) // 调试日志
  currentMessages.value.push(userMessage)
  
  try {
    const response = await chatAPI.sendMessage(currentSessionId.value, text)
    
    // 更新会话ID(如果是新会话)
    if (!currentSessionId.value) {
      currentSessionId.value = response.data.session_id
    }
    
    // 添加助手回复（确保role正确）
    const assistantMessage = {
      role: 'assistant',  // 明确设置为'assistant'
      content: response.data.response,
      intent: response.data.intent,
      tool_calls: response.data.tool_calls,
      created_at: new Date().toISOString()
    }
    console.log('添加助手消息:', assistantMessage) // 调试日志
    currentMessages.value.push(assistantMessage)
    
    // 重新加载会话列表(更新时间)
    await loadSessions()
    
  } catch (error) {
    console.error('发送消息失败:', error)
    message.error('发送消息失败: ' + (error.response?.data?.detail || error.message))
    
    // 移除失败的用户消息
    const lastMessage = currentMessages.value[currentMessages.value.length - 1]
    if (lastMessage && lastMessage.role === 'user' && lastMessage.content === text.trim()) {
      currentMessages.value.pop()
    }
  } finally {
    sending.value = false
  }
}

// 页面加载时初始化
onMounted(() => {
  loadSessions()
})
</script>

<style scoped>
/* 主布局样式已在模板中定义 */
</style>

